﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ResilienceCompute.Tool
{
    public class SignalFilter
    {
        // 复合滤波方案（移动平均 + 异常值过滤）
        public static List<double> HybridFilter(List<double> rawData,
            int windowSize = 7, double threshold = 150)
        {
            var stage1 = RemoveSpikes(rawData, threshold);
            return MovingAverage(stage1, windowSize);
        }

        // 移动平均滤波核心
        private static List<double> MovingAverage(List<double> data, int windowSize)
        {
            var filtered = new List<double>();
            int halfWin = windowSize / 2;

            for (int i = 0; i < data.Count; i++)
            {
                int start = Math.Max(0, i - halfWin);
                int end = Math.Min(data.Count - 1, i + halfWin);

                double sum = 0;
                for (int j = start; j <= end; j++)
                    sum += data[j];

                filtered.Add(sum / (end - start + 1));
            }
            return filtered;
        }

        // 动态阈值异常值过滤
        private static List<double> RemoveSpikes(List<double> data, double threshold)
        {
            var cleaned = new List<double>(data);
            for (int i = 1; i < data.Count - 1; i++)
            {
                double deltaPrev = Math.Abs(data[i] - data[i - 1]);
                double deltaNext = Math.Abs(data[i] - data[i + 1]);

                if (deltaPrev > threshold && deltaNext > threshold)
                    cleaned[i] = (data[i - 1] + data[i + 1]) / 2;
            }
            return cleaned;
        }
    }
}